﻿using System;
using System.ComponentModel;
using System.Xml;
using System.Xml.Linq;
using MassIntellect.WorkIt;
using MassIntellect.WorkIt.Frames;

namespace AIS2.Frames
{
	public class TBCMessageWriter : ServiceDependedFrame<IDAServiceTBCMsg>
	{
		private Guid SessionID = Guid.NewGuid();

		[Serialize(IgnoreDefault = true)]
		public string MessageKey { get; set; }

		[Serialize]
		public string MessageIDKey { get; set; }

		[Serialize]
		public string RegistrationSystemName { get; set; }

		[Serialize]
		public string TransportName { get; set; }

		[Serialize]
		public string MessageType { get; set; }

		[Serialize]
		public string MessageSource { get; set; }

		[Serialize]
		public string MessageName { get; set; }

		protected override void protectedPulse(PulseArgs args)
		{
			if (GetService() != null)
				PushMessage((XElement)args[GetKeyOrDefault(MessageKey, "Message")],
					(Guid?)args[GetKeyOrDefault(MessageIDKey, "MessageID")]
					);
			else
				ThrowException(new Exception("Ошибка доступа к базе."));
		}

		private void PushMessage(XElement msg, Guid? messID)
		{
			using (var db = Service.GetContext())
			{
				int? ret = 0;
				db.InsertMessage(RegistrationSystemName, 
					TransportName, DateTime.Now, 
					MessageType, 
					(messID ?? Guid.NewGuid()).ToString(), 
					MessageSource, DateTime.Now, 
					msg, ref ret, MessageName);
			}
		}
	}
}